package com.mall.security;


import com.central.common.utils.ResponseUtil;
import com.central.log.annotation.UserOperationLog;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.mall.entity.SecurityUser;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.security.core.Authentication;
import org.springframework.security.web.authentication.AuthenticationSuccessHandler;
import org.springframework.stereotype.Component;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.HashMap;
import java.util.List;
import java.util.concurrent.TimeUnit;

@Component
public class LoginSuccessHandler implements AuthenticationSuccessHandler {

    @Autowired
    private TokenManager tokenManager;

    @Autowired
    private ObjectMapper objectMapper;

    @Autowired
    private RedisTemplate redisTemplate;

    @Override
    @UserOperationLog(operModul = "登陆",operType = "登陆",operDesc = "登陆")
    public void onAuthenticationSuccess(HttpServletRequest request, HttpServletResponse response, Authentication authentication) throws IOException, ServletException {
        //获取当前用户信息
        SecurityUser user = (SecurityUser)authentication.getPrincipal();
        //根据用户名生成token
        String token = tokenManager.createToken(user.getCurrentUserInfo().getUsername());
        //获取到权限列表转成json
        List<String> permissionValueList = user.getPermissionValueList();

        String permissionListStr = objectMapper.writeValueAsString(permissionValueList);
        //将用户名和权限列表存到redis
        redisTemplate.boundHashOps("permission").put(user.getCurrentUserInfo().getUsername(),permissionListStr);
        //将用户信息存到redis
        String userStr = objectMapper.writeValueAsString(user.getCurrentUserInfo());
        redisTemplate.boundValueOps(user.getCurrentUserInfo().getUsername()).set(userStr,10,TimeUnit.HOURS);
        //返回前端
        response.setHeader("Content-type", "text/html;charset=UTF-8");
        HashMap<String, Object> map = new HashMap<>();
        map.put("token",token);
        map.put("username",user.getCurrentUserInfo().getUsername());
        ResponseUtil.responseSucceed(objectMapper,response,map);
    }
}
